package MainTest;

import javax.sound.midi.*;
import java.util.Scanner;

public class MiniMusicCmdLine {
    public static void main(String[] args) {
        MiniMusicCmdLine mini = new MiniMusicCmdLine();
        Scanner data1;
        while(true) {
            System.out.println("请输入三个参数(第一个参数为999则结束):");          
            data1 = new Scanner(System.in);
            if (Integer.parseInt(data1.next())==999){
                break;
            }else{
                if (data1.hasNextInt()){
                    int instrument = Integer.parseInt(data1.next());
                    if(data1.hasNextInt()){
                        int note = Integer.parseInt(data1.next());
                        mini.play(instrument, note);
                    }else{
                        System.out.println("非法第三个输入");
                    }
                }else{
                    System.out.println("非法第二输入");
                }                               
            }
        }
        System.out.println("break!");
        data1.close();
    }
    public void play(int instrument , int note) {
        try{
            //取得Sequence并将其打开
            Sequencer player = MidiSystem.getSequencer();
            player.open();
            //
            Sequence seq = new Sequence(Sequence.PPQ,4);
            //要求取得track
            Track track = seq.createTrack();

            //对track加入几个midievent,要注意的是setmessage的参数,以及midievent的constructor
            ShortMessage first = new ShortMessage();
            first.setMessage(192,1,instrument,0);
            MidiEvent changeInstrument = new MidiEvent(first,1);
            track.add(changeInstrument);

            ShortMessage a = new ShortMessage();
            a.setMessage(144,1,note,100);
            MidiEvent noteOn = new MidiEvent(a,1);
            track.add(noteOn);

            ShortMessage b = new ShortMessage();
            a.setMessage(128,1,note,100);
            MidiEvent noteOff = new MidiEvent(b,6);
            track.add(noteOff);

            player.setSequence(seq);
            player.start();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
